package org.emailclassifier.extractdb;

import org.emailclassifier.extractdb.EmailParser;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

/**
 * Batch processes e-mails in a directory structure, automatically using directory names as category.
 * 
 * @author Lourens Elzinga
 *
 */
public class BatchProcessor {
	
	public BatchProcessor()
	{
		m_categories = new HashMap<String, ArrayList<EmailParser>>();
	}
	
	/**
	 * Processes a directory, loading all emails contained within.
	 * The directory names are treated as category labels.
	 * @param basePath The base path to process
	 */
	public void process(String basePath)
	{
		File f = new File(basePath);
		if (!f.isDirectory())
			return;	// TODO: Make this an exception
		
		m_categories.clear();
		
		processFile(f);
	}
	
	/**
	 * Processes a file entry (directory or otherwise)
	 * If f is a directory, all sub-directories will be processed, otherwise the file will be parsed.
	 * @param f The File to process
	 */
	private void processFile(File f)
	{
		if (f.isDirectory())
		{
			String[] list = f.list();
			for (int i = 0; i < list.length; i++) {
				// Do not include hidden directories (i.e. .svn)
				if (list[i].startsWith(".")) continue;
				processFile(new File(f.getAbsolutePath() + "/" + list[i]));
			}
		} else {
			if (f.getParent() == null)
				return;
			
			String category = f.getParentFile().getName();
			EmailParser parser = new EmailParser();
			parser.parseEmail(f.getAbsolutePath());
			
			if (m_categories.containsKey(category)) {
				ArrayList<EmailParser> list = m_categories.get(category);
				list.add(parser);
			} else {
				ArrayList<EmailParser> list = new ArrayList<EmailParser>();
				list.add(parser);
				
				m_categories.put(category, list);
			}			
			
		}
		
	}
	
	/**
	 * Returns the amount of categories loaded
	 * @return The amount of categories
	 */
	public int getCategoryCount()
	{
		return m_categories.size();
	}
	
	/**
	 * Returns the total amount of emails loaded
	 * @return The total amount of emails loaded
	 */
	public int getTotalEntries()
	{
		int qty = 0;
		Iterator<Entry<String, ArrayList<EmailParser>>> it = m_categories.entrySet().iterator();
		while (it.hasNext())
		{
			Entry<String, ArrayList<EmailParser>> entry = it.next();
			qty += entry.getValue().size();			
		}
		return qty;
	}
	
	/**
	 * Returns the set of category names
	 * @return The set of category names
	 */
	public String[] getCategories()
	{	
		return m_categories.keySet().toArray(new String[0]);
	}
	
	/**
	 * Returns the array of emails belonging to the specified category
	 * @param category Category to return the emails from
	 * @return Array of emails belonging to category
	 */
	public EmailParser[] getEmails(String category)
	{
		return m_categories.get(category).toArray(new EmailParser[0]);		
	}
	
	
	private HashMap<String, ArrayList<EmailParser>> m_categories;

}
